package easy;

import java.util.HashMap;
import java.util.Map;

public class Solution_1995 {

    /*public int countQuadruplets(int[] nums) {
        int count = 0;
        for (int i = 0; i < nums.length - 3; i++) {
            for (int j = i + 1; j < nums.length - 2; j++) {
                for (int k = j + 1; k < nums.length - 1; k++) {
                    int sum = nums[i] + nums[j] + nums[k];
                    for (int p = k + 1; p < nums.length; p++) {
                        if (sum == nums[p]) {
                            count++;
                        }
                    }
                }
            }
        }
        return count;
    }*/

    public int countQuadruplets(int[] nums) {
        int res = 0;
        int len = nums.length;
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = len - 3; i >= 1; i--) {
            for (int j = len - 1; j > i+1; j--) {
                map.put(nums[j] - nums[i+1], map.getOrDefault(nums[j] - nums[i+1], 0) + 1);
            }
            for (int j = i - 1; j >= 0; j--) {
                res += map.getOrDefault(nums[i] + nums[j], 0);
            }
        }
        return res;
    }

    public static void main(String[] args) {
        Solution_1995 model = new Solution_1995();
//        System.out.println(model.countQuadruplets(new int[]{1, 2, 3, 6}));
//        System.out.println(model.countQuadruplets(new int[]{3, 3, 6, 4, 5}));
        System.out.println(model.countQuadruplets(new int[]{1, 1, 1, 3, 5}));
//        System.out.println(model.countQuadruplets(new int[]{9, 6, 8, 23, 39, 23}));
//        System.out.println(model.countQuadruplets(new int[]{28, 8, 49, 85, 37, 90, 20, 8}));
    }
}
